package us.icitap.commandcenter;

import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import us.icitap.commandcenter.business.AppUser;
import us.icitap.commandcenter.business.Result;
import us.icitap.commandcenter.business.ejb.AppStatelessBean;
import us.icitap.commandcenter.business.ejb.IAppStatefulBean;
import us.icitap.commandcenter.business.ejb.IAppStatelessBean;
import us.icitap.commandcenter.business.ejb.IPersistenceBean;
import us.icitap.commandcenter.business.ejb.persistence.CommandCenter;
import us.icitap.commandcenter.ui.configuration.CallReasonLayout;
import us.icitap.commandcenter.ui.configuration.DispatcherConfigLayout;
import us.icitap.commandcenter.ui.custom.CustButton;
import us.icitap.commandcenter.ui.configuration.GradeLayout;
import us.icitap.commandcenter.ui.dispatcher.DispatcherVerticalLayout;
import us.icitap.commandcenter.ui.operator.OperatorVerticalLayout;
import us.icitap.commandcenter.ui.supervisor.SupervisorVerticalLayout;
import us.icitap.commandcenter.utils.PortalEJBProperties;
import us.icitap.timsportal.ejb.remote.PortalBeanRemote;
import us.icitap.timsportal.entity.PortalSession;
import us.icitap.timsportal.entity.User;

import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;


/**
 * Main UI class
 */
@Theme("commandcentertheme")
@SuppressWarnings("serial")
@Title("Command Center")
@PreserveOnRefresh
public class CommandCenterUI extends UI {
	private static final String PORTAL_LOCATION = "http://192.168.3.199:8080/TimsPortalWEB/";
	private static final String PORTAL_SESSION_ID = "portalSessionId";
	private static final String MODULE_SESSION_ID = "moduleSessionId";

	OperatorVerticalLayout operatorLayout;
	DispatcherVerticalLayout dispatcherLayout;
	SupervisorVerticalLayout supervisorLayout;
	CallReasonLayout callReasonLayout;
	DispatcherConfigLayout dispatcherConfigLayout;
	GradeLayout gradeLayout;
	
	public final static Logger LOG = Logger.getLogger("CommandCenter_LOG");
	
	
	final CCMenuBar menubar = new CCMenuBar(this);
	final Panel panel = new Panel();
	
	public static PortalBeanRemote portalBeanRemote;
	
	public static IPersistenceBean persistenceBean;
	
	public static IAppStatelessBean appStatelessBean;
	
	private String loginMsg = "";
	
	
	@Override
	protected void init(VaadinRequest request) {
		
		
//		if(!validateEntry(request)){
//			getUI().getPage().setLocation(PORTAL_LOCATION);  
//			System.out.println(loginMsg);			      
//			// Close the VaadinSession
//			getSession().close();
//			return;			
//		}
		

		CommandCenterUI.LOG.info("HYRA");
		this.loadResources();
		//this.loadUser();	
		Result<AppUser> result =  appStatelessBean.login();
		if(result.isSucceeded())
			this.getUI().getSession().setAttribute(AppUser.class, result.getObject());
		else
			LOG.severe(result.getMessage());
			
		this.loadUI();
	}
	
	
	private boolean validateEntry(VaadinRequest request) {
		System.out.println(0);
		boolean noQueryString = request.getParameter("portalSessionId") == null;
		if (noQueryString) {
			System.out.println(1);
			loginMsg = "Nuk ka parameter portalSessionId";
			// kthe ne portal
			return false;
		} else {
			String portalSessionIdParam = request.getParameter("portalSessionId");
			String moduleSessionId = request.getWrappedSession().getId();
			
			if (portalSessionIdParam == null || "".equals(portalSessionIdParam)) {
				System.out.println(2);
				loginMsg = "Parametri portalSessionId eshte null";
				// nuk eshte hyr nga portali, hyrje direkte
				// kthe ne portal
				return false;
			}
			loadPortalEjb();
			PortalSession portalSession = portalBeanRemote
					.searchUserSessionInDB(portalSessionIdParam);
			
			System.err.println(portalSession);
			
			
			if (portalSession == null) {
				System.out.println(3);
				loginMsg = "Nuk eshte hyr nga portali";
				// nuk eshte hyr nga portali
				// kthe ne portal
				return false;
			}
			if (portalSession.getModuleEntrySuccess()!=null) {
				if(portalSession.getModuleEntrySuccess()) {
					System.out.println(4);
					loginMsg = "hyrje e mbyllur";
					// hyrje e mbyllur
					// kthe ne portal
					return false;
				}				
			}			
//			if (moduleSessionId.equals(portalSession.getModuleSessionId())) {
//				System.out.println(4);
//				loginMsg = "hyrje e mbyllur";
//				// hyrje e mbyllur
//				// kthe ne portal
//				return false;
//			}

			User user = portalBeanRemote.getModuleUser(portalSessionIdParam,
					moduleSessionId);
			if (user == null) {
				System.out.println(5);
				loginMsg = "Hyrje e vonuar";
				// shum von //ka kalu 1 min
				// kthe portal
				return false;
			}
			
			getSession().setAttribute(MODULE_SESSION_ID, moduleSessionId);
			getSession().setAttribute(PORTAL_SESSION_ID, portalSessionIdParam);
			getSession().setAttribute("username", user.getUsername());
			return true;
		}
	}
	
	private void loadUI(){
		this.addStyleName("sfond");
		
		final VerticalLayout layout = new VerticalLayout();
		layout.setMargin(false);
		setContent(layout);
		layout.addStyleName("head");
		Resource res = new ThemeResource("img/timsLogo.jpg");
		Image image = new Image(null, res);
		layout.addComponent(image);
		
		layout.setSizeUndefined();
		layout.setWidth("100%");
		
		CustButton closeBtn = new CustButton("Portal");
		closeBtn.addClickListener(new Button.ClickListener() {			
			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				String url = PORTAL_LOCATION 
				+ "?" +	PORTAL_SESSION_ID +"="
				+ getSession().getAttribute(PORTAL_SESSION_ID).toString()
				+ "&" + MODULE_SESSION_ID +"="
				+ getSession().getAttribute(MODULE_SESSION_ID).toString();
				getUI().getPage().setLocation(url); 
				getSession().getSession().setMaxInactiveInterval(0);
			}
		});
		
		HorizontalLayout hl = new HorizontalLayout();
		hl.setSizeFull();
		hl.addComponent(menubar);
		hl.addComponent(closeBtn);
		hl.setExpandRatio(menubar, 1);
		
		layout.addComponent(hl);
		
		
		layout.addComponent(panel);
		
		panel.addStyleName("panelCaption");
		panel.addStyleName("cust-margin-10");
		
		
		panel.setWidth("99%");
		
		VerticalLayout vl = new VerticalLayout();
		vl.setSizeFull();
		vl.setHeight("600px");
		
		panel.setContent(vl);
		
		panel.getContent().addStyleName("logo");
		
		
		VerticalLayout footerVl = new VerticalLayout();
		footerVl.setHeight("50px");
		footerVl.addStyleName("footer");
		if(getUser().getCommandCenter() != null){
			Label ccName = new Label(getUser().getCommandCenter().getName());
			ccName.addStyleName("ccLabel");
			ccName.setSizeUndefined();
			footerVl.addComponent(ccName);
			footerVl.setComponentAlignment(ccName, Alignment.BOTTOM_RIGHT);
			
		}
		layout.addComponent(footerVl);
		
		this.addDetachListener(new DetachListener() {

			@Override
			public void detach(DetachEvent event) {
				System.out
						.println("CommandCenterUI.init(...).new DetachListener() {...}.detach()");

			}
		});
	}
	
	
	
	private void loadPortalEjb() {
		InitialContext init;
		try {

			init = new InitialContext(PortalEJBProperties.getInitProperties());
			portalBeanRemote = (PortalBeanRemote) init.lookup("PortalBean#us.icitap.timsportal.ejb.remote.PortalBeanRemote");
			
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	
	private void loadResources() {

		InitialContext init;
		try {
			init = new InitialContext();
			
			//appStatefulBean = (IAppStatefulBean) init.lookup("java:global/CommandCenter/AppStatefulBean");
			appStatelessBean = (IAppStatelessBean) init.lookup("java:global/CommandCenter/AppStatelessBean");
			persistenceBean = (IPersistenceBean) init.lookup("java:global/CommandCenter/PersistenceBean");
				
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	private void resetLayout(){
		this.panel.setContent(null);
		this.operatorLayout = null;
		this.dispatcherLayout = null;
		this.supervisorLayout = null;
		this.callReasonLayout = null;
		this.dispatcherConfigLayout = null;
		this.gradeLayout = null;
	}
	
	public void loadDispatcherConfigLayout(){
		this.resetLayout();
		this.dispatcherConfigLayout = new DispatcherConfigLayout();
		panel.setContent(this.dispatcherConfigLayout);
		panel.setCaption("KONFIGURIMI");
	}
	public void loadOperatorLayout(){
		this.resetLayout();
		operatorLayout = new OperatorVerticalLayout();
		panel.setContent(operatorLayout);
		panel.setCaption("OPERATOR");
	}
	
	public void loadDispatcherLayout(){
		this.resetLayout();
		dispatcherLayout = new DispatcherVerticalLayout();
		panel.setContent(dispatcherLayout);
		panel.setCaption("SHPERNDARES");
	}

	public void loadSupervisorLayout(){
		this.resetLayout();
		supervisorLayout = new SupervisorVerticalLayout();
		panel.setContent(supervisorLayout);
		panel.setCaption("SUPERVIZOR");
	}


	public void loadCallReasonLayout(){
		this.resetLayout();
		callReasonLayout = new CallReasonLayout();
		panel.setContent(callReasonLayout);
		panel.setCaption("KONFIGURIMI");
	}
	
	public void loadGradeLayout(){
		this.resetLayout();
		gradeLayout = new GradeLayout();
		panel.setContent(gradeLayout);
		panel.setCaption("KONFIGURIMI");
	}
	
	public static AppUser getUser(){
		return (AppUser)CommandCenterUI.getCurrent().getSession().getAttribute(AppUser.class.getName());
	}
}